﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SayisalAnaliz.Library
{
    public static class MatrisInvers
    {

        private static double[,] MatrisOku(string matrisMetin)
        {
            double[,] matris = null;
            string[] satirlar = matrisMetin.Split(new string[] { Environment.NewLine,"\n" }, StringSplitOptions.None);
            matris = new double[satirlar.Length, satirlar.Length];

            for (int i = 0; i < satirlar.Length; i++)
            {
                string[] sutunlar = satirlar[i].Split(null);

                if (sutunlar.Length > satirlar.Length)
                    return null;

                for (int j = 0; j < sutunlar.Length; j++)
                {
                    matris[i, j] = Convert.ToDouble(sutunlar[j]);

                }
            }
            return matris;
        }
        public static string Uygula(string matris)
        {
            string tersi = "";

            double[,] a = MatrisOku(matris);


            double d, k;
            int i, j, x, y = (int)Math.Sqrt(a.Length);

            double[,] b = new double[y, y];
            double[,] c = new double[y, y];
            for (i = 0; i < y; i++)
            {
                for (j = 0; j < y; j++)
                {
                    if (i == j)
                        b[i, j] = 1;
                    else
                        b[i, j] = 0;
                }
            }
            if (a[0, 0] == 0)
            {
                for (j = 0; j < y; j++)
                {
                    c[0, j] = a[1, j];
                    a[1, j] = a[0, j];
                    a[0, j] = c[0, j];
                    c[0, j] = b[1, j];
                    b[1, j] = b[0, j];
                    b[0, j] = c[0, j];
                }
            }

            for (i = 0; i < y; i++)
            {
                d = a[i, i];
                for (j = 0; j < y; j++)
                {
                    a[i, j] = a[i, j] / d;
                    b[i, j] = b[i, j] / d;
                }
                for (x = 0; x < y; x++)
                {
                    if (x != i)
                    {
                        k = a[x, i];
                        for (j = 0; j < y; j++)
                        {
                            a[x, j] = a[x, j] - (a[i, j] * k);
                            b[x, j] = b[x, j] - (b[i, j] * k);
                        }
                    }
                }
            }


            for (i = 0; i < y; i++)
            {
                for (j = 0; j < y; j++)
                    tersi += b[i, j].ToString().Substring(0,3)+ " " ;
                tersi += "\n";
            }
            return tersi;
        }
    }
}
